const app = getApp()
var question_js = require('../../utils/question.js');
var hlshost="https://kaoshi.diuber.cn/PHPmvc/index.php?";
var payHost="https://kaoshi.diuber.cn/PHPmvc/wxpayv3/index.php";
Page({
  data: {
    bannerList: [],
    firstCategory1: [],
    firstCategory2: [],
    notice: '',
    categoryList: [],
    safeAreatop: wx.getSystemInfoSync().safeArea.top,
    nav: 2, //2网约车 1巡游车
    index: 0, //索引,
    questioncount:110,
    q_update_time: 60, //考试时间
    show:false,  //购买或实名认证弹窗
    toasttype:3//弹窗类型
  },
  onLoad() {
    var that = this;
    
    //请求轮播图数据
    wx.Apis.api.bannerList((code, data) => {
      that.setData({
        bannerList: data,
        notice: wx.getStorageSync('notice'),
      })
    });
    //一级分类
    wx.Apis.api.firstShowCategory((code, data) => {
      let firstCategory1 = [];
      let firstCategory2 = [];
      if (data.length < 4) {
        for (let i = 0; i < 3; i++) {
          firstCategory1.push(data[i]);
        }
        //firstCategory1.push({'id':0,'name':'更多','pic_url':''})
      } else {
        for (let i = 0; i < 4; i++) {
          firstCategory1.push(data[i]);
        }
        if (data.length >= 8) {
          for (let i = 4; i < 7; i++) {
            firstCategory2.push(data[i]);
          }
        } else {
          for (let i = 4; i < data.length; i++) {
            firstCategory2.push(data[i]);
          }
        }
        //firstCategory2.push({'id':0,'name':'更多','pic_url':'https://treasure.mambaxin.com/uploads/question/20221110/636d1b7192033.png'})
      }
      that.setData({
        firstCategory1: firstCategory1,
        firstCategory2: firstCategory2,
        nav: firstCategory1[0].cid
            
      })
     this.checkQuestion()
    });
    this.login();
  },
  onShow() {
    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        myCategory: wx.getStorageSync('myCategory')
      })
     
    }
    this.isbindphone();
  },
  setnav(e) {
    this.setData({
      nav: e.currentTarget.dataset.nav,
      index: e.currentTarget.dataset.index
    })
    this.checkQuestion()
  },
  goCategry(t) {
    var id = t.currentTarget.dataset.id.id;
    app.globalData.mainActiveIndex = id;

    wx.navigateTo({
      url: '/pages/detail/detail?id=' + t.currentTarget.dataset.id.cid + '&name=' + t.currentTarget.dataset.id.cname + '&time=' + t.currentTarget.dataset.id.ctime
    })

    // wx.switchTab({
    //   url: '/pages/category/category',
    // })

  },
  goDetail(t) {
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + t.currentTarget.dataset.id + '&name=' + t.currentTarget.dataset.name + '&time=' + t.currentTarget.dataset.time
    })
  },
  checkQuestion() {
    wx.showLoading({
      title: '加载中....',
    })
    var that = this;
    var question = wx.getStorageSync('question_' + that.data.nav);
    this.setData({
        questioncount: question.length
      })
    //console.log(question);
    if (!question) {
      that.uploadQuestion();
    } else {
         var question_update_time = wx.getStorageSync('question_update_time_' + that.data.nav)
      if (question_update_time < parseInt(that.data.q_update_time)) {
         that.uploadQuestion();
      } else {
        question_js.initAllQuestionFromStorage(that.data.nav);
        setTimeout(function () {
          wx.hideLoading({})
        }, 1000);
      }
    }
  },

  uploadQuestion() {
        var that = this;
    wx.Apis.api.getQuestionList(that.data.nav, (code, data) => {
      wx.setStorageSync('question_id_' + that.data.nav, data.question_id)
      wx.setStorageSync('question_' + that.data.nav, data.question_list)
      wx.setStorageSync('question_update_time_' + that.data.nav, data.q_update_time)
      question_js.initAllQuestionFromStorage(that.data.nav);
     
      setTimeout(function () {
        wx.hideLoading({})
      }, 1000);
    })
  },
  onShareAppMessage: function () {
    return {
      title: "新⽼司机宝典，⽹约⻋好帮⼿!",
      path: "pages/index/index",
      imageUrl: "/images/share.png"
    };
  },
  isbindphone:function(){
    wx.request({
      url : hlshost+"c=bindphone&m=query",
      method: "POST",
      data: {
           uid:wx.getStorageSync('userInfo').uid
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
          if (res.data.isbindphone==0){
            wx.setStorageSync('isbindphone',0);
          }else{
            wx.setStorageSync('isbindphone',1);
          }
      },
    })

  },
  login() {
    var that = this;
    var uid = wx.getStorageSync('userInfo').uid;
    var phone=wx.getStorageSync('userInfo').phone;
      wx.login({
        success(res) {
          if (res.code) {
            console.log(res.code)
            wx.Apis.login.login(res.code, (code, data) => {
              console.log(data);
              console.log(data.openid);
              wx.Apis.setUid(data.openid); //openid
              wx.Apis.set('openid', data.openid);
              wx.setStorageSync('userInfo', data);
            });
          }
        }
      });
    
  },
  isrenzheng(){
      //是否实名认证或已经购买考试权限
      var that=this;
    wx.request({
        url:  hlshost+"c=renzheng&m=query3", 
        method: 'POST',
        header: {
            "Content-Type": "application/x-www-form-urlencoded"
          }, 
        data:{uid:wx.getStorageSync('userInfo').uid},
        success: (res) => {

            if  (res.data.renzheng==1||res.data.buy_exam==1){
                wx.navigateTo({
                    url: '/pages/examhome/examhome?id=' + this.data.nav + '&action=exam&q_update_time=60'
                });
            }else{
                wx.setStorageSync('nav', this.data.nav);
                console.log("显示或实名认证弹窗");
                //显示弹窗
                that.setData({
                    show:true,
                    toasttype:3//弹窗类型
                })
            }
        },
        fail: (err) => {
          console.error('fail：', err);
        }
      });
  },
  pay(){
    var that =this;
      wx.request({
        url: payHost, 
        method: 'POST', 
        data: {
          openid:wx.getStorageSync('openid'),
          orderId: '1234567895756758' ,
          jine: 0.01,
          pay_name:'购买考试权限费'
        },
        success(res) {
          //console.log(res.data);
          wx.requestPayment({
            timeStamp: res.data.timeStamp + '',
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: 'MD5',
            paySign: res.data.sign,
            success: function (res) {
                //更新数据库
                wx.request({
                    url: hlshost+"c=buy&m=index",
                    method: 'POST',
                    header: {
                        "Content-Type": "application/x-www-form-urlencoded"
                      }, 
                    data: {
                         uid: wx.getStorageSync('userInfo').uid,
                         paymode:2//支付的是购买考试权限的费用
                    },
                    success: function(res) {
                        if (res.data.code==0){
                            that.setData({
                                show:false,
                                current:0,
                                canquestionnum:1000000//相当于无限题目
                            });
                            wx.showToast({
                                title: '支付成功',
                                icon: 'success',
                                duration: 3000
                            });
                        }
                    }
                  });
            },
            fail: function (res) {
               console.log(res);
            },
            'complete': function (res) {
               console.log('complete');
            }
           });
        },
        fail(err) {
          console.error('获取支付参数失败', err);
        }
      });
   },
   //实名认证
   renzheng(){
        wx.navigateTo({
            url: '/pages/about/name/index',
        })
   },
   setshow(){
    this.setData({
      show:!this.data.show
    });
  }
})